import _ from 'underscore'
import $ from 'jquery'

import dispatcher from 'lib/dispatcher'
import TimeStore from 'lib/stores/time-store'
import {Scope} from 'lib/scopeFactory'
import {coreApi,request} from '../apis/core-util'
// import {imsiApi,createGridOrder,parseToPartIMSIGrid} from '../apis/imsi-grid-util'
import {tracelistApi,createGridOrder,parseToPartGrid} from '../apis/tracelist'

let tabs = { 1: 'crashlog', 2: 'webview'} // index: key
export default class RootScope extends Scope {
  constructor(props){
    super(props);
    // console.log('props',props);
    // console.log('props.routeParams',props.routeParams);
    this.userId = decodeURIComponent(props.routeParams.userIdentifier)
    this.deviceId = props.routeParams.deviceId
    this.$state = {
      webview_module: 'jsError', // jsError, ajaxError, ajaxTrace
      currentTab: parseInt(props.params.tab) || 1,
      hasAjax:false,
      grid_crashlog: {
        loading:true,
        getOrder:createGridOrder('timestamp',-1),
        // fetch:this.fetchGrid.bind(this)
      },
      grid_webview: {
        loading:true,
        getOrder:createGridOrder('timestamp',-1),
      },
      // TODO
      // backend api for anr in imsisearch NOT ready
      // grid_anr: {
      //   loading:true
      // }
    }
    this.tabApis = {
      'crashlog': tracelistApi({
          urlName:'custom/userinfos',
          limit:10,
          userIdentifier:this.userId,
          deviceId:this.deviceId,
          dataType:BlueWare.platform.toLowerCase()==='android'?1:2,
          // order:'appVersion',
          // orderModel:'desc'
        },
        TimeStore.getValue,
        this.$state.grid_crashlog.getOrder),
      'webview': tracelistApi({
          urlName:'custom/userinfos',
          limit:10,
          userIdentifier:this.userId,
          deviceId:this.deviceId,
          dataType:this.$state.webview_module.toLowerCase()==='jserror'?5:(this.$state.webview_module.toLowerCase()==='ajaxerror'?7:8),
          // order:'appVersion',
          // orderModel:'desc'
        },
        TimeStore.getValue,
        this.$state.grid_webview.getOrder
      ),
      // TODO
      // backend api for anr in imsisearch NOT ready
      // 'anr': coreApi({})
    }
  }

  $switch_tab({ key, index }) {
    let _this = this
    this.$state.currentTab = index;
    let webview_module = this.$state.webview_module;

    if (index === 2) {

      request('/mobile/menu/tree.json').then((res) => {
        let childMenuOfWebview = _.filter(res[0].children, item => item.menuName === 'webview')[0].children;
        if (_.find(childMenuOfWebview, item => item.menuName === 'ajax')) {
          this.$state.hasAjax = true;
        }
        this.emit();
        // console.log('_this.$state',_this.$state)
      },function(){
        console.log('menu-fetching failed！')
      })

      let tabApi = tracelistApi({
            urlName:'custom/userinfos',
            limit:10,
            userIdentifier:this.userId,
            deviceId:this.deviceId,
            dataType:webview_module.toLowerCase()==='jserror'?5:(webview_module.toLowerCase()==='ajaxerror'?7:8),
            // order:'appVersion',
            // orderModel:'desc'
          }, TimeStore.getValue, createGridOrder('timestamp',-1))
      tabApi.fetch().then((rawData, params) => {
        _this.$state['grid_webview'] = parseToPartGrid(rawData, params)
        //this.$state['grid_webview'] = parseToPartIMSIGrid(rawData.data, params)
        _.each(_this.$state['grid_webview'].data, p => _.extend(p, {webview_module: _this.$state.webview_module
        }))
        this.emit()
      })
    }
    else {
      //
      let tabApi = this.tabApis[key];
      tabApi.fetch().then((rawData, params) => {
        this.$state['grid_' + key] = parseToPartGrid(rawData, params)
        //this.$state['grid_' + key] = parseToPartIMSIGrid(rawData.data, params)
        this.emit()
      })
    }
  } // $switch_tab

  $change_webview_module({ module_name }) {
    this.$state.webview_module = module_name;
    let tabApi = tracelistApi({
          urlName:'custom/userinfos',
          limit:10,
          userIdentifier:this.userId,
          deviceId:this.deviceId,
          dataType:module_name.toLowerCase()==='jserror'?5:(module_name.toLowerCase()==='ajaxerror'?7:8),
          // order:'appVersion',
          // orderModel:'desc'
        }, TimeStore.getValue, createGridOrder('timestamp',-1))
        // }, TimeStore.getValue, this.$state.grid_webview.getOrder)
    tabApi.fetch().then((rawData, params) => {
      this.$state['grid_webview'] = parseToPartGrid(rawData, params)
      //this.$state['grid_webview'] = parseToPartIMSIGrid(rawData.data, params)
      _.each(this.$state['grid_webview'].data, p => _.extend(p, {webview_module: this.$state.webview_module
      }))
      this.emit()
    })
  } // $change_webview_module

  $settime(){
    // console.log('this.viewInstance.props.location.pathname',this.viewInstance.props.location.pathname.split('/'))
    // let basePath = this.viewInstance.props.location.pathname.split('/').slice(0, 3);
    // console.log('basePath', basePath)
    let index = this.viewInstance.props.location.pathname.split('/')[4] ? parseInt(this.viewInstance.props.location.pathname.split('/')[4]) : 1
    // this.viewInstance.props.history.pushState(null, basePath.join('/')+'/'+index);

    this.$switch_tab({key: tabs[index], index: index})
    // this.$switch_tab({key: tabs[this.$state.currentTab], index: this.$state.currentTab})
  }

  $load(){
    this.$switch_tab({key: tabs[this.$state.currentTab], index: this.$state.currentTab})
  }
}
